package com.lapelittle.order.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.lapelittle.order.entity.AfterSaleOrder;
import com.lapelittle.order.mapper.AfterSaleOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class AfterSaleOrderImportService {
    private static final Logger logger = LoggerFactory.getLogger(AfterSaleOrderImportService.class);
    
    @Autowired
    private AfterSaleOrderMapper afterSaleOrderMapper;
    
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), AfterSaleOrder.class, new ReadListener<AfterSaleOrder>() {
            // 用于批量处理的临时列表
            private List<AfterSaleOrder> list = new ArrayList<>();
            
            @Override
            public void invoke(AfterSaleOrder order, AnalysisContext context) {
                list.add(order);
                // 达到100条数据批量处理一次
                if (list.size() >= 100) {
                    saveData();
                }
            }
            
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 确保最后的数据也被保存
                saveData();
            }
            
            private void saveData() {
                if (!list.isEmpty()) {
                    for (AfterSaleOrder order : list) {
                        // 检查售后单号是否存在
                        AfterSaleOrder existingOrder = afterSaleOrderMapper.findByAfterSaleNo(order.getAfterSaleNo());
                        if (existingOrder != null) {
                            // 更新现有记录
                            afterSaleOrderMapper.update(order);
                        } else {
                            // 插入新记录
                            afterSaleOrderMapper.insert(order);
                        }
                    }
                    logger.info("成功处理{}条数据", list.size());
                    list.clear();
                }
            }
        }).sheet().doRead();
    }
} 